package client;
import java.io.*;
import java.net.*;
import java.util.*;

import msgs.*;
/**
 * Listens for objects from the server
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */
public class ServerListener extends Thread implements TTConstants {
	/**
	 * The incoming msg queue from the server
	 */
	protected static Vector<ClientMsg> inQ;
	
	private static boolean go;
	private ServerSocket ssock;
	private Socket sock;
	private ObjectInputStream ois;
	private ClientMsg cmsg;
	
	/**
	 * Constructs a listener thread on the requested port
	 * @param p2 port to listen on
	 */
	public ServerListener(int p2) {
		inQ = new Vector<ClientMsg>();
		go = true;
		try {
			ssock = new ServerSocket(p2);
		}
		catch (IOException e) {
			go = false;
			System.err.println("Unable to open port " + p2 + " for listening!");
		}
	}
	
	public void run() {
		while (go) {
			try {
				// process inQ, block until we get a connection
				sock = ssock.accept();
				ois = new ObjectInputStream(sock.getInputStream());
				cmsg = (ClientMsg) ois.readObject();
				inQ.add(cmsg);
				ois.close();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}

		try {
			ois.close();
			sock.close();
			ssock.close();
		}
		catch(Exception e) {}
	}
	
	/**
	 * Cleanly shuts down the serverlistener
	 */
	public static void killServerListener() {
		while (go) {
			if (inQ.isEmpty()) go = false;
			else try {
				Thread.sleep(10);
			} 
			catch (Exception e) {}
		}
	}
}